$(function () {
  let layer = layui.layer;
  let form = layui.form;
  let indexAdd;
  let indexedit;

  function renderPage() {
    $.ajax({
      url: '/my/article/cates',
      method: 'get',
      success(res) {
        console.log(res);
        if (res.status === 0) {
          let htmlStr = template('tpl-table', res);
          $('tbody').html(htmlStr)
        }
      }
    });
  }
  renderPage()

  //文章添加的弹出层
  $('#btnAddCate').on('click', function () {
    indexAdd = layer.open({
      type: 1,
      area: ['500px', '250px'],
      title: '添加文章分类',
      content: $('#dialog-add').html()
    })
  });
  //文章添加的确认按钮
  $('body').on('click', '#form-addbtn', function (e) {
    e.preventDefault();
    $.ajax({
      method: "post",
      url: '/my/article/addcates',
      data: {
        name: $('#form-add [name=name]').val(),
        alias: $('#form-add  [name=alias]').val()
      },
      success(res) {
        if (res.status === 0) {
          layer.close(indexAdd)
          renderPage()
        }
      }
    })
  })

  //文章编辑的弹出层
  $('body').on('click', '.btn-edit', function () {
    indexedit = layer.open({
      type: 1,
      area: ['500px', '250px'],
      title: '修改文章分类',
      content: $('#dialog-edit').html()
    })
    let id = $(this).attr('data-id')
    $.ajax({
      method: 'GET',
      url: '/my/article/cates/' + id,
      success(res) {
        form.val('form-edit', res.data)
      }
    })
  })

  // 给编辑form绑定事件
  $('body').on('submit', '#form-edit', function (e) {
    e.preventDefault();
    $.ajax({
      method: 'post',
      url: '/my/article/updatecate',
      data: $(this).serialize(),
      success(res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message, { icon: 2 })
        }
        layer.msg(res.message, { icon: 1 })
        layer.close(indexedit)
        renderPage()
      }
    })
  })

  // 删除功能
  $('tbody').on('click', '.btn-delete', function () {
    let id = $(this).attr('data-id')
    layer.confirm('能确定要删除吗?', { icon: 3, title: '提示' }, function (index) {
      $.ajax({
        method: 'GET',
        url: '/my/article/deletecate/' + id,
        success(res) {
          if (res.status !== 0) {
            return layer.msg(res.message, { icon: 2 })
          }
          layer.msg(res.message, { icon: 1 })
          layer.close(index);
          renderPage()
        }
      })

    });

  })

})
